#include <memory>

#include "XM_EvLoopTeaPod.hh"
#include "XM_EvLoopThread.hh"

XM_NAMESPACE_BEGIN

EvLoopTeaPod::EvLoopTeaPod(EvLoop* lop, const std::string& nameArg)
: elop__(lop),
name__(nameArg),
started__(false),
threadNum__(0),
next__(0)
{}

EvLoopTeaPod::~EvLoopTeaPod()
{} // Don't delete loop, it is stack variable

void EvLoopTeaPod::start(const ThreadInitCallback& cb)
{
    started__ = true;

    for (int i = 0; i < threadNum__; ++i)
    {
        char buf[name__.size() + 32];
        snprintf(buf, sizeof(buf),
            "%s%d", name__.c_str(), i
        );

        EvLoopThread* elt = new EvLoopThread(cb, buf);
        threads__.push_back(std::unique_ptr<EvLoopThread>(elt));
        loops__.push_back(elt->startLoop());
    }

    if (threadNum__ == 0 && cb)
        cb(elop__);
}

EvLoop* EvLoopTeaPod::getNextLoop()
{
    EvLoop* lop = elop__;

    if (!loops__.empty())
    {
        lop = loops__[next__];
        ++next__;

        if (next__ >= loops__.size())
            next__ = 0;
    }

    return lop;
}

std::vector<EvLoop*> EvLoopTeaPod::getAllLoops()
{
    if (loops__.empty())
        return std::vector<EvLoop*>(1, elop__);
    else return loops__;
}

XM_NAMESPACE_END